package com.fire.eyes.util;

import java.net.URL;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.protocol.Protocol;

/**
 *
 * @author Aspire
 * @date 2018-04-18
 */
public class HttpUtils {

	private static final String HTTPS = "https";
	public static String request(String in, String httpUrl, int timeout)throws Exception {
 		PostMethod postmethod = new PostMethod(httpUrl);
		URL url = new URL(httpUrl);
		if(url.getProtocol().equals(HTTPS)){
            Protocol https = new Protocol(HTTPS, new SslProtocolSocketFactory(), url.getPort()==-1?443:url.getPort());
            Protocol.registerProtocol(HTTPS, https);
        }
		String responseBodyAsString = "";
		try {
			postmethod.setRequestBody(in);
			postmethod.setRequestHeader("Content-type", "application/json;charset=UTF-8");
			
			System.out.println("请求服务开始...");
			System.out.println("转发bia-middle服务URL=" + url);
			
			// 指定请求内容的类型
			HttpClient httpclient = new HttpClient();
			HttpClientParams httparams = new HttpClientParams();
			// int timeout = 0;
			if (timeout <= 0) {
				timeout = 10* 1000;
			}
			httparams.setSoTimeout(timeout);
			httpclient.setParams(httparams);
			int result = httpclient.executeMethod(postmethod);
			System.out.println("转发服务结束,返回结果代码=" + result);
			byte[] cont = postmethod.getResponseBody();
			String re = new String(cont, "UTF-8");
			postmethod.releaseConnection();
			postmethod = null;
			responseBodyAsString = re;
		}catch (Exception e) {
			throw e;
		} finally {
			if (postmethod != null) {
				try {
					postmethod.releaseConnection();
					postmethod = null;
				} catch (Exception e1) {
					
				}
			}
		}
		return responseBodyAsString;

	}

}
